package team.freeroom.hotelmanage.controller;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import team.freeroom.hotelmanage.repository.entity.Authority;
import team.freeroom.hotelmanage.repository.entity.Menu;
import team.freeroom.hotelmanage.controller.model.LoginUser;
import team.freeroom.hotelmanage.repository.entity.Role;
import team.freeroom.hotelmanage.repository.entity.User;
import team.freeroom.hotelmanage.service.AuthorityService;
import team.freeroom.hotelmanage.service.MenuService;
import team.freeroom.hotelmanage.service.RoleService;
import team.freeroom.hotelmanage.service.UserService;
import team.freeroom.hotelmanage.util.CpachaUtil;
import team.freeroom.hotelmanage.util.MenuUtil;

@Controller
@RequestMapping("/system")
public class SystemController {

    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    @Autowired
    private AuthorityService authorityService;

    @Autowired
    private MenuService menuService;

    /**
     * 系统登录后的主页
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public ModelAndView index(ModelAndView model, HttpServletRequest request) {
        List<Menu> userMenus = (List<Menu>) request.getSession().getAttribute("userMenus");
        model.addObject("topMenuList", MenuUtil.getAllTopMenu(userMenus));
        model.addObject("secondMenuList", MenuUtil.getAllSecondMenu(userMenus));
        model.setViewName("system/index");
        return model;
    }

    /**
     * 登陆页面
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public ModelAndView login(ModelAndView model) {
        model.setViewName("system/login");
        return model;
    }

    /**
     * 登录表单提交处理控制器
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> loginAct(@Valid LoginUser user, BindingResult bindingResult, HttpServletRequest request) {
        Map<String, String> ret = new HashMap<String, String>();

        // 登录参数校验
        if (user == null) {
            ret.put("type", "error");
            ret.put("msg", "请填写用户信息！");
            return ret;
        }
        if (bindingResult.hasErrors()) {
            ret.put("type", "error");
            ret.put("msg", bindingResult.getAllErrors().get(0).getDefaultMessage());
            return ret;
        }

        // 验证码校验
        Object loginCpacha = request.getSession().getAttribute("loginCpacha");
        if (loginCpacha == null) {
            ret.put("type", "error");
            ret.put("msg", "会话超时，请刷新页面！");
            return ret;
        }
        if (!user.getCpacha().toUpperCase().equals(loginCpacha.toString().toUpperCase())) {
            ret.put("type", "error");
            ret.put("msg", "验证码错误！");
            return ret;
        }

        // 验证用户名和密码
        User findByUsername = userService.findByUsername(user.getUsername());
        if (findByUsername == null) {
            ret.put("type", "error");
            ret.put("msg", "该用户名不存在！");
            return ret;
        }
        if (!user.getPassword().equals(findByUsername.getPassword())) {
            ret.put("type", "error");
            ret.put("msg", "密码错误！");
            return ret;
        }

        // 用户名密码及验证码都正确
        // 此时需要查询用户的角色权限
        Role role = roleService.find(findByUsername.getRoleId());
        // 根据角色获取权限列表
        List<Authority> authorityList = authorityService.findListByRoleId(role.getId());
        String menuIds = "";
        for (Authority authority : authorityList) {
            menuIds += authority.getMenuId() + ",";
        }
        if (!StringUtils.isEmpty(menuIds)) {
            // 去掉最后一个逗号
            menuIds = menuIds.substring(0, menuIds.length() - 1);
        }
        List<Menu> userMenus = menuService.findListByIds(menuIds);

        //把角色信息、菜单信息放到session中
        request.getSession().setAttribute("admin", findByUsername);
        request.getSession().setAttribute("role", role);
        request.getSession().setAttribute("userMenus", userMenus);
        ret.put("type", "success");
        ret.put("msg", "登录成功！");
        return ret;
    }

    /**
     * 后台退出注销功能
     */
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String logout(HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.setAttribute("admin", null);
        session.setAttribute("role", null);
        request.getSession().setAttribute("userMenus", null);
        return "redirect:login";
    }

    /**
     * 修改密码页面
     */
    @RequestMapping(value = "/edit_password", method = RequestMethod.GET)
    public ModelAndView editPassword(ModelAndView model) {
        model.setViewName("system/edit_password");
        return model;
    }

    @RequestMapping(value = "/edit_password", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> editPasswordAct(String newpassword, String oldpassword, HttpServletRequest request) {
        Map<String, String> ret = new HashMap<String, String>();
        if (StringUtils.isEmpty(newpassword)) {
            ret.put("type", "error");
            ret.put("msg", "请填写新密码！");
            return ret;
        }
        User user = (User) request.getSession().getAttribute("admin");
        if (!user.getPassword().equals(oldpassword)) {
            ret.put("type", "error");
            ret.put("msg", "原密码错误！");
            return ret;
        }
        user.setPassword(newpassword);
        if (userService.editPassword(user) <= 0) {
            ret.put("type", "error");
            ret.put("msg", "密码修改失败，请联系管理员！");
            return ret;
        }
        ret.put("type", "success");
        ret.put("msg", "密码修改成功！");
        return ret;
    }

    /**
     * 本系统所有的验证码均采用此方法
     *
     * @param cpachaType:用来区别验证码的类型，传入字符串
     */
    @RequestMapping(value = "/get_cpacha", method = RequestMethod.GET)
    public void generateCpacha(
            @RequestParam(name = "vl", required = false, defaultValue = "4") Integer vcodeLen,
            @RequestParam(name = "w", required = false, defaultValue = "100") Integer width,
            @RequestParam(name = "h", required = false, defaultValue = "30") Integer height,
            @RequestParam(name = "type", required = true, defaultValue = "loginCpacha") String cpachaType,
            HttpServletRequest request,
            HttpServletResponse response) {
        CpachaUtil cpachaUtil = new CpachaUtil(vcodeLen, width, height);
        String generatorVCode = cpachaUtil.generatorVCode();
        request.getSession().setAttribute(cpachaType, generatorVCode);
        BufferedImage generatorRotateVCodeImage = cpachaUtil.generatorRotateVCodeImage(generatorVCode, true);
        try {
            ImageIO.write(generatorRotateVCodeImage, "gif", response.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
